package Maybe;

import java.util.PriorityQueue;

class Mytimertask implements Comparable<Mytimertask>{
    private long time;
    private Runnable task;
    public Mytimertask(Runnable task,long time){
        this.task=task;
        this.time=time;
    }
    public void run(){
        task.run();
    }
    public long gettime(){
        return time;
    }

    @Override
    public int compareTo(Mytimertask o) {
        return (int)(o.time-this.time);
    }
}
class Mytimer{
    Object locker=new Object();
    PriorityQueue<Mytimertask> queue=new PriorityQueue<>();
    public void schedule(Runnable task,long delay){
        synchronized(locker){
            Mytimertask task1=new Mytimertask(task,System.currentTimeMillis()+delay);
            queue.offer(task1);
            locker.notifyAll();
        }
    }
    public Mytimer(){
        Thread t=new Thread(()->{
            synchronized(locker){
                while(true){
                    while(queue.isEmpty()){
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    Mytimertask task=queue.peek();
                    if(task.gettime()>System.currentTimeMillis()){
                        try {
                            locker.wait(task.gettime()-System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else{
                        task.run();
                        queue.poll();
                    }
                }
            }

        });
        t.start();
    }
}



public class may {
    public static void main(String[] args) {
        Mytimer mytimer=new Mytimer();
        mytimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);
        mytimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);

    }
}
